<script lang="ts" setup>
import { watch, nextTick, ref } from "vue";
import UserBubble from "./widget/user-bubble.vue";
import RobotBubble from "./widget/robot-bubble.vue";
import RobotAudioBubble from "./widget/robot-audio-bubble.vue";
import RobotGoodBubble from "./widget/robot-good-bubble.vue";
import RobotArticleBubble from "./widget/robot-article-bubble.vue";
import RobotMediaBubble from "./widget/robot-media-bubble.vue";
import RobotPacketBubble from "./widget/robot-packet-bubble.vue";
import RedPackPopup from "./widget/redPackPopup.vue";
import OrderPopup from "./widget/orderPopup.vue";

import Prologue from "./widget/prologue.vue";
import useScrollView from "./useScrollView";
import debounce from "@/utils/debounce";
import { computed } from "vue";

interface AnswerList {
  content: string;
  id?: number;
  messages_id?: string;
  msg_type: number;
}
export interface ChatItemProps {
  created_at?: string;
  id?: number;
  messages_id?: number;
  msg?: string;
  question?: string;
  rb_robot_id?: number;
  type_name?: string;
  user_id?: number;
  productInfo?: any;
  answer_list?: AnswerList[];
}

const props = withDefaults(
  defineProps<{
    showHot?: boolean;
    hotList?: any;
    placeholder?: string;
    chats: Array<ChatItemProps>;
    conversationChat?: { robot: ChatItemProps; user: ChatItemProps } | null;
    userBubbleBgColor?: string;
    userBubbleTextColor?: string;
    robotBubbleBgColor?: string;
    robotBubbleTextColor?: string;
  }>(),
  {
    showHot: true,
    hotList: () => [],
    chats: () => [],
    conversationChat: null,
    userBubbleBgColor: undefined,
    userBubbleTextColor: undefined,
    robotBubbleBgColor: undefined,
    robotBubbleTextColor: undefined
  }
);
const emit = defineEmits([
  "load-more",
  "scroll",
  "select",
  "exchange",
  "scroll-bottom",
  "send-message"
]);

const redpackPopup = ref();
const orderPopup = ref();
const selectedGood = ref<any>({
  info: {},
  sku: []
});
const { intoView, scrollTop, scrollBottom } = useScrollView();

watch(
  [
    () => props.conversationChat?.robot.msg,
    () => props.conversationChat?.user.question
  ],
  () => {
    scrollBottom();
  }
);
watch(
  () => props.chats,
  async (newChats: any, oldChats: any) => {
    if (newChats) {
      await nextTick();
      if (!oldChats.length) {
        debounce(scrollBottom, 1000, false)();
      } else {
        scrollTop();
      }
    }
  }
);
const sendMessage = (text: string) => {
  emit("send-message", text);
};
const showButton = () => {
  emit("load-more");
};
const hideButton = () => {};

const onOrder = (good: any) => {
  selectedGood.value = good;
  orderPopup.value.open();
};

const offsetPlaceholderHeight = computed(() => {
  const res = uni.getSystemInfoSync();
  return res.statusBarHeight! + 60 + "px";
});
</script>
<template>
  <scroll-view
    :scroll-top="intoView"
    scroll-y
    scroll-anchoring
    class="chat-container"
    @scrolltoupper="showButton"
    @scrolltolower="hideButton"
  >
    <view id="content" class="chat-content">
      <!-- 占位 -->
      <view :style="{ height: offsetPlaceholderHeight }"></view>
      <Prologue v-if="showHot" @send-message="sendMessage" />

      <template v-for="(item, index) in chats" :key="index">
        <UserBubble
          v-if="item.question"
          :bg-color="props.userBubbleBgColor"
          :color="props.userBubbleTextColor"
          :appear="false"
          :message="item.question"
        ></UserBubble>
        <!-- 红包 -->
        <!-- <RobotPacketBubble isRecive @click="redpackPopup.onShow" /> -->
        <!-- 媒体 -->
        <!-- <RobotMediaBubble type="video" id="" url="" /> -->
        <!-- 文章 -->
        <!-- <RobotArticleBubble
          :article="{
            title: '文章标题描述不超9字',
            desc: '这是一条文章推送，点击详情可查看全部内容，文字超出时',
            id: '123',
            img: ''
          }"
        /> -->
        <!-- 语音 -->
        <!-- <RobotAudioBubble
          :bg-color="props.robotBubbleBgColor"
          :color="props.robotBubbleTextColor"
          :voice-url="
            index % 2 === 0
              ? 'https://engine-robot.lnkyeah.com/static/d7a4b9d04b8bd5f211565af31c16da86.mp3'
              : 'https://engine-robot.lnkyeah.com/static/8daf49ccd9fa51c59164ec746f32219a.mp3'
          "
        ></RobotAudioBubble> -->
        <template v-for="answer in item.answer_list" :key="answer.id">
          <!-- 文字 -->
          <RobotBubble
            v-if="answer.msg_type === 1"
            :bg-color="props.robotBubbleBgColor"
            :color="props.robotBubbleTextColor"
            :is-last="index === chats.length - 1"
            :load="false"
            :message="answer.content"
          ></RobotBubble>
          <!-- 商品 -->
          <RobotGoodBubble
            v-else-if="answer.msg_type === 4"
            :content="answer.content"
            @order="onOrder"
          />
        </template>
      </template>
      <UserBubble
        appear
        v-if="conversationChat?.user"
        :message="conversationChat.user.question"
        :bg-color="props.userBubbleBgColor"
        :color="props.userBubbleTextColor"
      ></UserBubble>
      <RobotBubble
        has-cursor
        v-if="conversationChat?.robot"
        :bg-color="props.robotBubbleBgColor"
        :color="props.robotBubbleTextColor"
        :isload="!conversationChat.robot.msg"
        :message="conversationChat.robot.msg || ''"
      ></RobotBubble>
    </view>
  </scroll-view>
  <RedPackPopup ref="redpackPopup" />
  <OrderPopup
    ref="orderPopup"
    :info="selectedGood.info"
    :sku="selectedGood.sku"
  />
</template>
<style lang="scss" scoped>
.chat-content {
  padding-bottom: 20rpx;
}
.chat-container {
  position: relative;
  width: 100%;
  height: 100%;
  overflow-y: scroll;
  overflow-x: hidden;
}
</style>
